<script setup lang="ts">
import type { UserDTO } from '@/index';
import { useUserStore } from '@/stores';
import { UserOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import type { FormInstance, Rule } from 'ant-design-vue/es/form';
import { useRequest } from 'vue-request';

interface FormState {
  nickname: string | undefined,
  avatarUrl: string | undefined
  intro: string | undefined
}


defineOptions({
  name: 'UserProfileModal'
})
const userStore = useUserStore()
const emit = defineEmits(['ok', 'cancel', "update:open"])
const open = defineModel<boolean>('open', { required: true })
const formState = reactive<FormState>({
  nickname: undefined,
  avatarUrl: undefined,
  intro: undefined
})
const rules: Record<string, Rule[]> = {
  nickname: [
    {
      required: true,
      message: "昵称不能为空"
    },
    {
      min: 2,
      max: 6,
      message: "昵称长度不能小于2,不能大于6"
    }
  ],
  intro: [
    {
      min: 1,
      max: 100,
      message: "简介最大长度不能超过100"
    }
  ]
}
const formRef = ref<FormInstance | null>(null)

const { run: updateUserByToken, loading: updateLoading } = useRequest(updateUserByTokenService, {
  onSuccess: ({ data }) => {
    if (data.code == RequestStatusCode.FAILURE) return message.error(data.message)
    message.success("更新用户信息成功")
    formRef.value?.resetFields()
    console.log("update userInfo:", data.data);

    userStore.setUserInfo({ ...data.data })
    emit('update:open', false)
  },
  onError: () => {
    message.error('更新用户信息失败')
  }
})

const { run: uploadAvatar, loading: uploadLoading } = useRequest(uploadAvatarService, {
  onSuccess: ({ data }) => {
    if (data.code == RequestStatusCode.FAILURE) return message.error(data.message)
    formState.avatarUrl = data.data
    message.success("上传头像成功")
  },
  onError: () => {
    message.error("上传用户头像失败")
  }
})

const handleSubmit = () => {
  if (!formRef.value) return
  formRef.value.validate().then((res) => {
    console.log("res:", res);
    updateUserByToken(res as UserDTO)
    console.log("校验通过：", res);
  })
}

// 选择文件组合式函数
const { onChange: handleChangeSelectAvatar, open: handleSelectAvatar } = useFileDialog({
  accept: "image/*",
  multiple: false
})


handleChangeSelectAvatar((files) => {
  if (!files) return
  formState.avatarUrl = useObjectUrl(files[0]).value
  // 上传文件
  const formData = new FormData()
  formData.append('file', files[0])

  uploadAvatar(formData)
})
const isLoading = computed(() => uploadLoading.value || updateLoading.value)


watch(() => userStore.userInfo, (newValue) => {
  console.log("newValueUserInfo:", newValue);
  if (!newValue) return
  const { avatarUrl, nickname, intro } = newValue
  formState.avatarUrl = avatarUrl
  formState.nickname = nickname
  formState.intro = intro
})
</script>

<template>
  <a-modal title="修改用户信息" v-model:open="open" ok-text="确认修改" cancel-text="取消" @ok="handleSubmit">
    <a-spin title="加载中" :spinning="isLoading">
      <div class="user-profile">
        <a-form ref="formRef" :model="formState" :rules="rules" layout="vertical" class="user-profile-form"
          scroll-to-first-error>
          <a-form-item name="avatarUrl">
            <div class="user-profile">
              <a-avatar :src="formState.avatarUrl" :size="140" @click="handleSelectAvatar">
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
            </div>
          </a-form-item>
          <a-form-item label="昵称:" name="nickname">
            <a-input autofocus placeholder="请输入您的昵称" v-model:value="formState.nickname" />
          </a-form-item>
          <a-form-item label="简介:" name="intro">
            <a-textarea placeholder="请输入您的简介" show-count auto-size :maxlength="100" v-model:value="formState.intro" />

          </a-form-item>
        </a-form>
      </div>
    </a-spin>
  </a-modal>
</template>

<style scoped lang="scss">
.user {
  &-profile {
    display: flex;
    justify-content: center;

    &-form {
      min-width: 70%;
    }
  }
}
</style>